// 聊天室SSE广播功能
// 进程内简单实现（MVP）。生产可替换为 Redis pub/sub。

export const chatSubscribers = new Map<string, Set<any>>();

export function sendToChatRoom(roomId: string, event: 'message'|'gift'|'system', payload: any) {
  const set = chatSubscribers.get(roomId);
  console.log(`[SSE] 尝试向房间 ${roomId} 发送 ${event} 事件`);
  console.log(`[SSE] 房间 ${roomId} 的订阅者数量:`, set?.size || 0);

  if (!set) {
    console.log(`[SSE] 房间 ${roomId} 没有订阅者`);
    return;
  }

  const data = `event: ${event}\n` + `data: ${JSON.stringify(payload)}\n\n`;
  console.log(`[SSE] 发送数据:`, data);

  let successCount = 0;
  let errorCount = 0;

  for (const res of set) {
    try {
      res.write(data);
      successCount++;
    } catch (error) {
      console.log(`[SSE] 连接已断开，移除订阅者:`, error);
      // 连接已断开，从订阅者列表中移除
      set.delete(res);
      errorCount++;
    }
  }

  console.log(`[SSE] 发送完成 - 成功: ${successCount}, 失败: ${errorCount}`);
}
